import { Component, OnInit,ElementRef } from '@angular/core';
import { Router,NavigationExtras } from '@angular/router'; 
import {ActivatedRoute} from '@angular/router'
import {HouseServiceSvr} from '../../services/houseServiceSvr'
import {CollectServiceSvr} from '../../services/CollectServiceSvr'
import {CustomerServiceSvr} from '../../services/customerServiceSvr'
import { getISOWeek } from 'date-fns';
import { en_US, NzI18nService, zh_CN } from 'ng-zorro-antd/i18n';
import {HouseViewingApplyServiceSvr} from '../../services/houseViewingApplyServiceSvr';
import { DatePipe } from '@angular/common';
import { NzMessageService } from 'ng-zorro-antd/message';
import { addDays } from 'date-fns';
import { formatDistance } from 'date-fns';
import {CommentServiceSvr} from '../../services/CommentServiceSvr'

@Component({
  selector: 'app-house-details',
  templateUrl: './house-details.component.html',
  styleUrls: ['./house-details.component.less']
})
export class HouseDetailsComponent implements OnInit {

  // 图片列表
   array = [
    {
      index:1,
      src:'../../../assets/img/home1.jpg'
    },
    {
      index:2,
      src:'../../../assets/img/home1.jpg'
    },
    {
      index:3,
      src:'../../../assets/img/home1.jpg'
    },
    {
      index:4,
      src:'../../../assets/img/home1.jpg'
    }
   ];
  //  
  effect = 'scrollx';
  // 房屋id
  HouseId:any
  // 用户姓名
  UserName:any=localStorage.getItem('customerNickName')
  DetailAddress:string=''
  HouseDetali:any
  // token
  token:any=localStorage.getItem('Token')
  // 用户id
  
  customerId:any=localStorage.getItem('customerId')
  constructor(
    private router:Router,
    private route: ActivatedRoute,
    private houseServiceSvr:HouseServiceSvr,
    private collectServiceSvr:CollectServiceSvr,
    private customerServiceSvr:CustomerServiceSvr,
    private i18n: NzI18nService,
    private houseViewingApplyServiceSvr:HouseViewingApplyServiceSvr,
    private el:ElementRef,
    private nzMessageService: NzMessageService,
    private message: NzMessageService,
    private commentServiceSvr:CommentServiceSvr
  ) {
    this.route.queryParams.subscribe((r: any) => {
      this.HouseId = r.valueOf().key;
      // console.log('houseId'+this.HouseId);
    })
  }

  ngOnInit(): void {
    // 房屋详情接口
    // this.customerId=localStorage.getItem('customerId')
    // this.UserName=this.UserName.replace("\"","").replace("\"","");
    // this.customerId=this.customerId.replace("\"","").replace("\"","");
    // this.token=this.token.replace("\"","").replace("\"","");
    if(this.customerId==null){
      this.customerId=''
      this.UserName=''
      this.token=''
    }else{
    this.customerId=this.customerId.replace("\"","").replace("\"","");
    this.UserName=this.UserName.replace("\"","").replace("\"","");
    this.token=this.token.replace("\"","").replace("\"","");
    }
    console.log('customerId:'+this.customerId);
    console.log('token:'+this.token);
    console.log('UserName:'+this.UserName);
    console.log('HouseId:'+this.HouseId);
    this.houseServiceSvr.getHouseByPrimaryKey(this.token,this.HouseId,true).then((res=>{
      console.log('房屋详情接口');
      this.HouseDetali=res
      this.rent=res.Rent
      this.DetailAddress=res.DetailAddress
      // console.log('housedetail'+this.rent);
    }))

    // 收藏房屋信息接口
    this.collectServiceSvr.listCollection(this.token,this.customerId).then((res)=>{
      console.log('收藏列表接口');
      // console.log(res);
      // this.CollectionId=res.
      for(let item of res._Items){
        if(item.Id==this.HouseId){
        this.collectionColor='#F0935F';
        this.iscollection=true
        this.CollectionId=item.CollectId
        // console.log('this.CollectionId'+this.CollectionId);
        }
      }
    })
    // 预约时间段接口
    this.houseViewingApplyServiceSvr.getApplyTime(this.token,this.HouseId).then((res)=>{
      // console.log(res);
      console.log('预约时间段接口');
      console.log('houseid'+this.HouseId);
      this.reverseArr=res._Items
    }).catch((err)=>{
      console.log('预约时间段:'+err.Msg);
    })
    // 查看是否预约接口
    this.houseViewingApplyServiceSvr.getApplyStatus(this.token,this.HouseId,this.customerId).then((res=>{
      // console.log('aa');
      console.log('查看是否预约接口');
      // console.log(res);
      if(res.Date!==''){
        this.isReverse=true
        this.reverseTimeTure=res['Time']
        this.reverseDateTure=res['Date']
        this.ReverseId=res['Id']
        console.log('data'+res['Date']);
        console.log('time'+res['Time']);
      }
    }))
    // 查看用户是否租房
    this.houseViewingApplyServiceSvr.hasReviewEligibility(this.token,this.customerId,this.HouseId).then((res)=>{
      console.log('用户是否有评论资格');
      console.log(res);
      if(res){
        this.isEligibilityComemt=true
      }else{
        this.isEligibilityComemt=false
      }
    })
    // 
    this.commentServiceSvr.listCommentsForFront(this.token,this.HouseId).then((res)=>{
      console.log('评论信息');
      console.log(res);
      this.data=res._Items
      console.log(this.data);
      
    })

    this.commentServiceSvr.getCommentScore(this.token,this.HouseId).then((res)=>{
      console.log('房屋评分');
      console.log(res);
      this.value=res
    })
  }
// 是否有资格评论
isEligibilityComemt:boolean=false
// 预约时间
reverseArr:any=[]
reverseTimeArr:any
// 双向绑定时间
reverseDay:string=''
reverseTime:string=''
// 预约后返回的真实预约时间
reverseTimeTure:string=''
reverseDateTure:string=''
// 是否清除选择框的值
isClearSearchValue:boolean=false

// 选择日期的选择框失去焦点事件
selectFoucus(){
  if(this.reverseDay==this.Toaydata){
    this.reverseTimeArr=this.reverseArr[0].Value._Items
  }else if(this.reverseDay==this.ToaydataAdd1){
    this.reverseTimeArr=this.reverseArr[1].Value._Items
  }else{
    this.reverseTimeArr=this.reverseArr[2].Value._Items
  }
  console.log('data'+this.Toaydata);
}
// 当天日期
Toaydata:string=new Date().toISOString().slice(0, 10);
// 加一天的日期
ToaydataAdd1:string=this.getNewData(this.Toaydata,1)


// 获得当前日期。并且加上指定天数
getNewData (time:any, days:any) {
  if(days === undefined || days === '') {
    days = 1;
  }
  let date =new Date(time);
  date.setDate(date.getDate() + days);
  let month = date.getMonth() + 1;
  let day = date.getDate();
  return date.getFullYear() +'-' + ('0'+ month).slice(-2)+'-' + ('0'+ day).slice(-2);
}



// 收藏图标颜色
collectionColor:string='#D9D9D9'
// 判断是否收藏
iscollection:boolean=false
// 收藏房屋id
CollectionId:string=''
//收藏图标变化
goCollection(){
// this.collectionColor='#F0935F'
if(this.token==''){
  // console.log('没得权限');
    this.nzMessageService.info('您没登录，无权限收藏房源');
}else{
  this.iscollection=!this.iscollection
if(this.iscollection==true){
this.collectionColor='#F0935F'
this.collectServiceSvr.saveCollection('',this.customerId,this.HouseId).then((res)=>{
  if(res==1){
    console.log('添加成功');
    this.message.info('添加成功');
  }
})
console.log('添加');

}else{
this.collectionColor='#D9D9D9'
console.log('删除');

this.collectServiceSvr.deleteCollection('',this.CollectionId).then((res)=>{
  if(res==1){
    console.log('删除成功');
    this.message.info('删除成功');
  }
})
}
}

}

 
  // 是否显示弹框
  isVisible = false;
  // 确认按钮
  isOkLoading = false;
// 预约按钮颜色
// reverseColor:string='#74b49b';
// 是否已经预约
isReverse:boolean=false;
// 预约id
ReverseId:string=''
  // 预约看房
  showModal(): void {
    if(this.token==''){
    this.nzMessageService.info('您没登录，无权限预约看房');
    }else{
      this.isVisible = true;
    }
  }
  // 点击确定回调
  handleOk(): void {
    this.isOkLoading = true;
    setTimeout(() => {
      this.isVisible = false;
      this.isOkLoading = false;
    }, 500);
    console.log('reverseDay'+this.reverseDay);
    console.log('reverseTime'+this.reverseTime);
    this.houseViewingApplyServiceSvr.saveHouseViewingApply('',this.customerId,this.UserName,this.HouseId,this.reverseDay,this.reverseTime).then((res)=>{
      console.log('res:'+res);
      if(res){
        this.isReverse=true
        console.log('预约返回结果');
      console.log(res);
      this.reverseDateTure=res['Date']
      this.reverseTimeTure=res['Time']
      this.ReverseId=res['Id']
      console.log('ReverseId'+this.ReverseId);
      }else{
        console.log('失败');
        this.nzMessageService.info('预约失败，请重新预约');
      }
    })
  }
  // 点击取消回调
  handleCancel(): void {
    this.isVisible = false;
  }




  // 日期参数
  date = null;
  isEnglish = false;

  // 时间发生变化的回调
  onChange(result: Date): void {
    console.log('onChange: ', result);
  }

  getWeek(result: Date): void {
    console.log('week: ', getISOWeek(result));
  }

  changeLanguage(): void {
    this.i18n.setLocale(this.isEnglish ? zh_CN : en_US);
    this.isEnglish = !this.isEnglish;
  }
  // 开始时间参数
  beaginTime: Date | null = null;
  // 当 [ngModel] 不存在时，可以设置面板打开时默认选中的值
  beagindefaultOpenValue = new Date(0, 0, 0, 0, 0, 0);
  // 开始时间参数
  endTime: Date | null = null;
  // 当 [ngModel] 不存在时，可以设置面板打开时默认选中的值
  enddefaultOpenValue = new Date(0, 0, 0, 0, 0, 0);



// 客户id
// customerId:string='3'
rent:any=''
// 判断用户是否实名认证再跳转到签订合同页面
  goCollectionPage(){
    const navigationExtras: NavigationExtras = {
      queryParams: {
        key: this.HouseId,
        custmerId: this.customerId,
        rent:this.rent,
        DetailAddress:this.DetailAddress
      }
    };

    if(this.token==''){
    this.nzMessageService.info('您没登录，无权限进行签约');
    }else{
      this.customerServiceSvr.getCustomerByPrimaryKey('',this.customerId).then((res)=>{
        console.log('客户信息');
        console.log(res.Authentication);
        if(res.Authentication==1){
          this.isVisible_sign = true;
          console.log('该会员未实名认证，不得签约');
          console.log('reverseArr');
          // console.log(this.reverseArr);
        }
        else{
          this.router.navigate(['/sign'],navigationExtras)
        }
      })
    }
  }


  isVisible_sign = false;

  handleOk_sign(): void {
    this.isVisible_sign = false;
  }

  handleCancel_sign(): void {
    this.isVisible_sign = false;
  }
  

// 确认取消预约弹窗
// 取消取消回调
cancel(): void {
  // this.nzMessageService.info('取消预约成功');
}
// 确认取消回调
confirm(): void {
  // this.nzMessageService.info('取消预约成功');
  this.isReverse=false
  console.log('this.ReverseId:'+this.ReverseId);
  
  this.houseViewingApplyServiceSvr.deleteHouseViewingApplyByPrimaryKey('',this.ReverseId).then((res)=>{
    console.log(res);
    if(res==1){
      // console.log('取消预约成功');
  this.nzMessageService.info('取消预约成功');
    }else{
      // console.log('取消预约失败');
  this.nzMessageService.info('取消预约失败');
    }
  })
}

// 轮播图左右跳转
goNext(){

}
goLast(){

}

// 评论
data:any
// data: any[] = [
//   {
//     author: 'Han Solo',
//     avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
//     content:
//       'We supply a series of design principles, practical patterns and high quality design resources' +
//       '(Sketch and Axure), to help people create their product prototypes beautifully and efficiently.',
//     datetime: '一天以前',
//     RateValue:3
//   },
//   {
//     author: 'Han Solo',
//     avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
//     content:
//       'We supply a series of design principles, practical patterns and high quality design resources' +
//       '(Sketch and Axure), to help people create their product prototypes beautifully and efficiently.',
//     datetime: '两天以前',
//     RateValue:2
//   }
// ];
// 房屋评分
value = 0;
tooltips = ['terrible', 'bad', 'normal', 'good', 'wonderful'];
submitting = false;
user = {
  author: 'Han Solo',
  avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png'
};
inputValue = '';
UserRateValue:number=0
RateChange(e:any){
  console.log('e:'+e);
  this.UserRateValue=e
}
handleSubmit(): void {
  if(this.isEligibilityComemt){
    this.submitting = true;
    const Comments = this.inputValue;
    const Score = this.UserRateValue;
    console.log('UserRateValue'+this.UserRateValue);
    // console.log('UserRateValue'+this.UserRateValue);
    this.inputValue = '';
    
    setTimeout(() => {
      this.submitting = false;
      this.commentServiceSvr.saveComment(this.token,this.customerId,this.HouseId,Comments,this.UserRateValue).then((res)=>{
        console.log(res);
        if(res==1){
          this.data = [
            ...this.data,
            {
              ...this.user,
              Comments,
              Score,
              // datetime: formatDistance(new Date(), new Date())
            }
          ]
        }
    this.UserRateValue=0
      })
    }, 800);

  }else{
    this.nzMessageService.info('亲爱的用户，看房后才有资格评论哦');
  }
}
}
